// @algorithm @lc id=100326 lang=cpp
// @title liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof

#include "algm/algm.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (headA == nullptr || headB == nullptr) {
            return nullptr;
        }
        ListNode *ptr1 = headA;
        ListNode *ptr2 = headB;
        bool flag1 = true;
        bool flag2 = true;
        bool fail = false;
        while (ptr1 != ptr2) {
            if (ptr1->next) {
                ptr1 = ptr1->next;
            }
            else if (flag1) {
                ptr1 = headB;
                flag1 = false;
            }
            else {
                fail = true;
                break;
            }
            if (ptr2->next) {
                ptr2 = ptr2->next;
            }
            else if (flag2) {
                ptr2 = headA;
                flag2 = false;
            }
            else {
                fail = true;
                break;
            }
        }
        return fail == true ? nullptr : ptr1;
    }
};